/*
 * gms_modem.c
 *
 */

#include "globe_var.h"
#include "config.h"
#include "memory.h"
#include "Queue.h"
#include "console.h"
#include "gps.h"
#include "xstring.h"
#include "tool.h"
#include "task.h"
#include "message.h"
#include <stdlib.h>
#include <stdio.h>
#include "LSM303DLH.h"
#include "led.h"
#include "gpsfix.h"
//#include "ADXL335.h"
#include "main.h"
#include "Murata.h"
#include "ELM327.h"
#include "MS5801.h"
#include "ADXL345.h"
#include "L3G4200D.h"
#include "HMC5883.h"
#include "CarState.h"
#include "imu_process.h"

#include "gsm_modem.h"

#include "command.h"

//#include "app.h"
//#include "pressure_sensor.h"
#include <math.h>



QBuf gGSM_TxQBuf;
QBuf gGSM_RxQBuf;

QBuf gGSM_Q_SendStringIdx;
QBuf gGsm_Q_StringBuf;

char gGsm_RespChk[GSM_STR_RESP_DTAT_LEN]={0};
char gGsm_RespChk_Sts=FAIL;

void GSM_PW_ON(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
    
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOE, &GPIO_InitStructure);

	GPIO_SetBits(GPIOE, GPIO_Pin_13);
}

void GSM_PW_OFF(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
    
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOE, &GPIO_InitStructure);

	GPIO_ResetBits(GPIOE, GPIO_Pin_13);
}


#define  USART2_GPIOx                    GPIOD
#define  USART2_RCC_APB2Periph_GPIOx     RCC_APB2Periph_GPIOD
#define  USART2_GPIO_RTSPin              GPIO_Pin_4
#define  USART2_GPIO_CTSPin              GPIO_Pin_3
#define  USART2_GPIO_TxPin               GPIO_Pin_5
#define  USART2_GPIO_RxPin               GPIO_Pin_6
void GSM_Init(void)
{
	NVIC_InitTypeDef	NVIC_InitStructure;
	GPIO_InitTypeDef	GPIO_InitStructure;
	//DMA_InitTypeDef		DMA_InitStructure;
		USART_InitTypeDef		USART_InitStructure;
	USART_ClockInitTypeDef	USART_ClockInitStructure;
	//	EXTI_InitTypeDef	EXTI_InitStructure;

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOE, &GPIO_InitStructure);



	/* USART2_REMAP */
	GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);

	//DMA_DeInit(DMA1_Channel6);
	USART_DeInit(USART2);

	/* Clock */
	  /* Enable GPIOx and AFIO clocks */
	RCC_APB2PeriphClockCmd(USART2_RCC_APB2Periph_GPIOx | RCC_APB2Periph_AFIO, ENABLE);

	/* Enable USART2 clocks */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

	/* Configure USART2 RTS and USART2 Tx as alternate function push-pull */
	GPIO_InitStructure.GPIO_Pin = USART2_GPIO_RTSPin | USART2_GPIO_TxPin;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_Init(USART2_GPIOx, &GPIO_InitStructure);

	/* Configure USART2 CTS and USART2 Rx as input floating */
	GPIO_InitStructure.GPIO_Pin = USART2_GPIO_CTSPin | USART2_GPIO_RxPin;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(USART2_GPIOx, &GPIO_InitStructure);



	/* UART2 Setting */
	USART_InitStructure.USART_BaudRate		= 38400;
	USART_InitStructure.USART_WordLength	= USART_WordLength_8b;
	USART_InitStructure.USART_StopBits		= USART_StopBits_1;
	USART_InitStructure.USART_Parity		= USART_Parity_No;
	//USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS_CTS;
	USART_InitStructure.USART_Mode			= USART_Mode_Rx | USART_Mode_Tx;
	
	USART_ClockInitStructure.USART_Clock		= USART_Clock_Disable;
	USART_ClockInitStructure.USART_CPOL			= USART_CPOL_Low;
	USART_ClockInitStructure.USART_CPHA			= USART_CPHA_2Edge;
	USART_ClockInitStructure.USART_LastBit		= USART_LastBit_Disable;
	
	
	USART_Init(USART2, &USART_InitStructure);
	USART_ClockInit(USART2, &USART_ClockInitStructure);
    USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
	USART_Cmd(USART2, ENABLE);


	QBuf_Init(&gGSM_TxQBuf, pGSMTxData, GSM_TX_SIZE);
	QBuf_Init(&gGSM_RxQBuf, pGSMRxData, GSM_RX_SIZE);

	QBuf_Init(&gGSM_Q_SendStringIdx, pGSMSTxStrngIDX, GSM_TX_STRING_IDX_SIZE);
	QBuf_Init(&gGsm_Q_StringBuf, pGSMTxStrngBuf, GSM_TX_STRING_BUF_SIZE);
	

	/* NVIC Setting */
	NVIC_InitStructure.NVIC_IRQChannel				= USART2_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority	= IRQ_USART2;
	NVIC_InitStructure.NVIC_IRQChannelCmd			= ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
	
    
	*pFlag_gsm_uart_tx_busy = 0;
}



//Support to GPRS_U_BLOX
void GSM_UART_IRQ_Tx(void)
{
    char buf;

	if (gGSM_TxQBuf.use != 0)
	{
		QBuf_Read(&gGSM_TxQBuf, &buf, 1);
		USART_SendData(USART2, buf);
	}
	else
	{
		USART_ITConfig(USART2, USART_IT_TXE, DISABLE);
		*pFlag_gsm_uart_tx_busy = 0;
	}
}

void GSM_UART_IRQ_Rx(void)
{
	char buf;

	buf = USART_ReceiveData(USART2);
	QBuf_Write(&gGSM_RxQBuf, &buf, 1);
}

unsigned short GsmUart_Read(char *buf, unsigned short count)
{
	if (count > gGSM_RxQBuf.use)
	{
		count = gGSM_RxQBuf.use;
	}
	QBuf_Read(&gGSM_RxQBuf, buf, count);
	return count;
}

void GsmUart_Write(char *buf, unsigned short count)
{
	//unsigned short remain;
	unsigned short iWait=0;
	char *temp;
	
	temp = buf;
#if 1
	do
	{

#if 1
		//wait until byte has been sent
		iWait=0;
		while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET)
        {
            if (++iWait > 5000)
            {
                //timeout on waiting trasmit register empty
                //  just move tail forward and drop one byte from buffer
                Console_Out256("Modem TXE Timeout\r\n");
                break;
            }
        }
#endif		
		//remain = gGSM_TxQBuf.len - gGSM_TxQBuf.use;

		//if (count < remain)
		//{
		//	remain = count;
		//}
	
		if (QBuf_Write(&gGSM_TxQBuf, temp, 1)==QBUF_FULL) Console_Out256("GsmTxBuf full\r\n");
	
		if (*pFlag_gsm_uart_tx_busy == 0)
		{
			*pFlag_gsm_uart_tx_busy = 1;
            USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
		}
		else
		{
			Console_Out256("GsmTx busy\r\n");
		}
		temp ++;
		count --;
	} while (count != 0);
#else
	do
	{

#if 1
		//wait until byte has been sent
		iWait=0;
		while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET)
        {
            if (++iWait > 5000)
            {
                //timeout on waiting trasmit register empty
                //  just move tail forward and drop one byte from buffer
                Console_Out256("Modem TXE Timeout\r\n");
                break;
            }
        }
#endif		
		remain = gGSM_TxQBuf.len - gGSM_TxQBuf.use;
		if (count < remain)
		{
			remain = count;
		}
		count -= remain;
		QBuf_Write(&gGSM_TxQBuf, temp, remain);
		temp += remain;
		if (*pFlag_gsm_uart_tx_busy == 0)
		{
			*pFlag_gsm_uart_tx_busy = 1;
            USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
		}
	} while (count != 0);
 #endif
}
/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send function
 * Argument(s): message buffer point
 * Return(s)  : PASS,FAIL
 * Note(s)    : Max buffer is 256
 * ----------------------------------------------------------------------------
 */
char qGsm_AtCmd(char *bufData,unsigned short pre_dly,unsigned short end_dly,char *rspData,unsigned short repWait)
{	char bufD[32];
//	int i;

	sprintf(bufD, "AT%s\r\n",bufData);
//	i=xstrlen(bufD);
	return qGsm_Send(bufD,pre_dly,xstrlen(bufD),end_dly,rspData,repWait);
}
/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send function
 * Argument(s): message buffer point
 * Return(s)  : Purn ASS,FAIL
 * Note(s)    : Max buffer is 256
 * ----------------------------------------------------------------------------
 */
char qGsm_Send(char *bufData,unsigned short pre_dly,unsigned short b_Len,unsigned short end_dly,char *rspData,unsigned short repWait)
{	
	unsigned char i;
	Gsm_SendString strBuf;
	//unsigned short qBufStr_len=b_Len;

	if (b_Len==0)
	{
		Console_Out256("GSM_Send_dataLen=0 Err:");
		Console_Out256(bufData);
		Console_Out256("\r\n");
		return FAIL;
	}
	else if (b_Len>GSM_SENDSTR_LEN)
	{
		b_Len=GSM_SENDSTR_LEN;
		Console_Out256("GSM_StrLEN over\r\n");
	}
	
	xmemset(&strBuf,0,sizeof(Gsm_SendString));
	strBuf.pre_delay=pre_dly;
	strBuf.dataLen=b_Len;
	strBuf.end_delay=end_dly;
	for (i=0;i<GSM_STR_RESP_DTAT_LEN;i++)
	{
		strBuf.respond_data[i]=rspData[i];
		if (rspData[i]==0) break;
	}
	strBuf.respond_WaitTimeOut=repWait;

	if ((QBuf_ChkFull(&gGsm_Q_StringBuf, b_Len))==QBUF_OK)
	{
		if (QBuf_Write(&gGSM_Q_SendStringIdx, (char*)&strBuf, sizeof(Gsm_SendString))==QBUF_OK)
		{
			QBuf_Write(&gGsm_Q_StringBuf,bufData,b_Len);
		}
		else
		{
			Console_Out256("QBuf_GSM_StrIdx Full\r\n");
			return FAIL;
		}
	}
	else
	{
		Console_Out256("QBuf_GSM_StrBuf Full\r\n");
		return FAIL;
	}

	return PASS;
}

/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send function
 * Argument(s): message buffer point
 * Return(s)  : None
 * Note(s)    : Max buffer is 256
 * ----------------------------------------------------------------------------
 */
void GsmUart_Send(char *buf)
{
	unsigned long buflen;
	buflen=xstrlen(buf);
	if (buflen>GSM_SENDSTR_LEN)
		buflen=GSM_SENDSTR_LEN;
	GsmUart_Write(buf,buflen);
	
}

/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send function
 * Argument(s): message buffer point
 * Return(s)  : None
 * Note(s)    : Max buffer is 256
 * ----------------------------------------------------------------------------
 */
void GsmUart_AT_CMGS(char *telNo,char *msg)
{
	char *strtmp;
	char cTrl_Z=ASC_SUB;
    strtmp = (char *)malloc(sizeof(char) * 256);
    assert_malloc(strtmp);

	xmemset((void *)strtmp, 0, 256);

	sprintf(strtmp, "AT+CMGS=%c%s%c\r\n",0x22,telNo,0x22);


	Console_Out256(strtmp);
	
	GsmUart_Send(strtmp);
	
	Delay_Sec(2);

	Console_Out256("SMS:\r\n");
	Console_Out256(msg);
	Console_Out256("\r\n");
	
	GsmUart_Send(msg);
	Delay_millisecond(1000);
	GsmUart_Write((char*)&cTrl_Z,1);

	Delay_Sec(4);
	GsmUart_Display(strtmp);

	free(strtmp);
	assert_free();
	
}

/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send function for Qbuffer
 * Argument(s): message buffer point
 * Return(s)  : None
 * Note(s)    : Max buffer is 256 
 				SMS message
 * ----------------------------------------------------------------------------
 */
void qGsm_AT_CMGS(char *telNo,char *msg)
{
	char *strtmp;
	char cTrl_Z=ASC_SUB;
    strtmp = (char *)malloc(sizeof(char) * GSM_SENDSTR_LEN);
    assert_malloc(strtmp);

	xmemset((void *)strtmp, 0, GSM_SENDSTR_LEN);

	sprintf(strtmp, "AT+CMGS=%c%s%c\r\n",0x22,telNo,0x22);


//	Console_Out256(strtmp);
	//GsmUart_Send(strtmp);
	qGsm_Send(strtmp,0,xstrlen(strtmp),1000,NULL,0);
	qGsm_Send("\r\n",0,2,0,">",1000);
	
//	Delay_Sec(2);

//	Console_Out256("SMS:\r\n");
//	Console_Out256(msg);
//	Console_Out256("\r\n");

	//GsmUart_Send(msg);
	qGsm_Send(msg,0,xstrlen(msg),1000,NULL,0);

//	Delay_millisecond(1000);
//	GsmUart_Write((char*)&cTrl_Z,1);
	if (qGsm_Send((char*)&cTrl_Z,0,1,300,"+CMGS",4000)==FAIL)
		Console_Out256("CTRL_Z Err\r\n");	

//	Delay_Sec(4);
//	GsmUart_Display(strtmp);

	free(strtmp);
	assert_free();
	
}
/*
 * ----------------------------------------------------------------------------
 * Description: GSM Read Display
 * Argument(s): message buffer point
 * Return(s)  : None
 * Note(s)    : Max buffer is 256
 * ----------------------------------------------------------------------------
 */
unsigned char GsmUart_Display(char *buf)
{
	unsigned short count;
	count = GsmUart_Read(buf, GSM_RX_SIZE);

	if (count!=0)
	{
	Delay_millisecond(500);
		Console_Write(buf,count);	//CMD_Parser(CONSOLE_PORT, buf, count);
		return PASS;
	}
	else
	{
		Console_Out256("GSM Loss AT\n\r");
		return FAIL;
	}
}


/*
 * ----------------------------------------------------------------------------
 * Description: GSM Send Test
 * Argument(s): None
 * Return(s)  : None
 * Note(s)    : None
 * ----------------------------------------------------------------------------
 */
void SendSMS_Test(void)
{
//rex SMS
//static unsigned long gps_Delay_time=0;
//if (pCMD->smsdst.interval_time<SMSDST_ITIME_LIMIT_MIN) return;
//if ((unsigned long)(gRTCSec-gps_Delay_time)>=pCMD->smsdst.interval_time)
{
	
//	gps_Delay_time=gRTCSec;
	char *strtmp;
    strtmp = (char *)malloc(sizeof(char) * 128);
    assert_malloc(strtmp);
		

//pUBX->STATUS.gpsFix=3;pUBX->POSLLH.lon=1215836330;pUBX->POSLLH.lat=250589330;

	sprintf(strtmp, "GPS:%d,%.6f,%.6f,%.2f\r\n", 
	pUBX->STATUS.gpsFix,(double)pUBX->POSLLH.lat*0.0000001,(double)pUBX->POSLLH.lon*0.0000001,(double)pUBX->POSLLH.hMSL*0.001);
	Console_Write(strtmp, strlen(strtmp));

	if (pUBX->STATUS.gpsFix!=0)
	{
		//"http://maps.google.com/maps?f=q&q=25.058933,121.583633"
		sprintf(strtmp, 	"height:%.2f\r\n"
							"Google Map:\r\n"
							"http://maps.google.com/maps?f=q&q=%.6f,%.6f",(double)pUBX->POSLLH.hMSL*0.001,(double)pUBX->POSLLH.lat*0.0000001,(double)pUBX->POSLLH.lon*0.0000001);

	if (xstrlen(pCMD->smsdst.num)>=10)
		{
			GsmUart_AT_CMGS(pCMD->smsdst.num,strtmp);
		}

		//GsmUart_AT_CMGS(TELPHONE_NO,strtmp);
	}
	
	free(strtmp);
    assert_free();
}	
}

/* ----------------------------------------------------------------------------
 * Description: GSM Send to Modem process
 * Argument(s): None
 * Return(s)  : None
 * Note(s)    : None
 * ----------------------------------------------------------------------------
 */
#define	GSMSEND_STS_INIT		(0)
#define	GSMSEND_STS_PRE_DLY		(1)
#define	GSMSEND_STS_DATAPROC	(2)
#define	GSMSEND_STS_END_DLY		(3)
#define	GSMSEND_STS_RESP_CHK	(4)

void GsmSend_Process(void)
{

//	Gsm_SendString strBuf;
//	unsigned short bLen;
	static char gGsmSend_RunStats=GSMSEND_STS_INIT;
	static Gsm_SendString gsmSendIdx;
	char * gsm_strtmp;
	gsm_strtmp = (char *)malloc(sizeof(char) * GSM_SENDSTR_LEN);
    assert_malloc(gsm_strtmp);

	xmemset(gsm_strtmp,0,GSM_SENDSTR_LEN);
	
	switch (gGsmSend_RunStats)
	{
		case GSMSEND_STS_INIT:
		{
			if (QBuf_Read(&gGSM_Q_SendStringIdx, (char *)&gsmSendIdx, sizeof(Gsm_SendString))==QBUF_EMPTY)
			{
				if (gGsm_Q_StringBuf.use!=0) 
				{
					QBuf_Clear(&gGsm_Q_StringBuf);
					Console_Out256("GSM_Q_Buf SendProcess Err1\r\n");
				}
			}
			else
			{	//it is OK
				gGsmSend_RunStats=GSMSEND_STS_PRE_DLY;
				gSystick_GSMDLY=gsmSendIdx.pre_delay;
			}
			break;
		}
		case GSMSEND_STS_PRE_DLY:
		{
			if (gSystick_GSMDLY==0) 
				gGsmSend_RunStats=GSMSEND_STS_DATAPROC;
			
			break;

		}
		case GSMSEND_STS_DATAPROC:
		{
			if (QBuf_Read(&gGsm_Q_StringBuf,gsm_strtmp,gsmSendIdx.dataLen)==QBUF_EMPTY)
			{
				Console_Out256("GSM_Q_Buf SendProcess Err2\r\n");
			}
			else
			{
				if (gsmSendIdx.dataLen>GSM_SENDSTR_LEN)
				{
					gsmSendIdx.dataLen=GSM_SENDSTR_LEN;
					Console_Out256("GSM_Q_Buf DataLen Err\r\n");
				}
				if (gsm_strtmp[0]==ASC_SUB)
				{
					Console_Out256("^Z\r\n");
				}
				else
				{
					Console_Out256("GSM_Send:\r\n");
					Console_Out256(gsm_strtmp);
					Console_Out256("\r\n");
				}
				GsmUart_Write(gsm_strtmp,gsmSendIdx.dataLen);
			}
			
			gGsmSend_RunStats=GSMSEND_STS_END_DLY;
			gSystick_GSMDLY=gsmSendIdx.end_delay;
			break;
		}
		case GSMSEND_STS_END_DLY:
		{
			
			if (gSystick_GSMDLY==0)
			{
				gGsmSend_RunStats=GSMSEND_STS_RESP_CHK;
				gSystick_GSMDLY=gsmSendIdx.respond_WaitTimeOut;
				gGsm_RespChk_Sts=FAIL;

				xmemcpy(gGsm_RespChk,gsmSendIdx.respond_data,GSM_STR_RESP_DTAT_LEN);
				if (gGsm_RespChk[0]!=0) //NULL
				{
					Console_Out256("GSM Chk:");
					Console_Out256(gGsm_RespChk);
					Console_Out256("\r\n");
				}
			}
			
			break;
		}
		case GSMSEND_STS_RESP_CHK:
		{
			if (gSystick_GSMDLY>(60000*2)) 
			{
				gSystick_GSMDLY=0;
				Console_Out256("GSM_Resp_Timeout Err\r\n");
			}
			if (gGsm_RespChk_Sts==PASS||gSystick_GSMDLY==0)
			{
				if (gGsm_RespChk[0]!=0) //NULL
				{
					if (gGsm_RespChk_Sts==FAIL)
						Console_Out256("GSM_Resp_Chk_Fail\r\n");
				}
				gGsmSend_RunStats=GSMSEND_STS_INIT;
				gGsm_RespChk[0]=0;
			}
			break;
		}
		default:
			break;
	}		
	
	free(gsm_strtmp);
    assert_free();



//	GsmUart_Write(buf,buflen);
//	GsmUart_Send(char * buf)

	
}


/* ----------------------------------------------------------------------------
 * Description: GSM Recvice parser process
 * Argument(s): None
 * Return(s)  : None
 * Note(s)    : None
 * ----------------------------------------------------------------------------
 */
void GsmRecv_Parser(void)
{
	static char gsmStr[GSM_RX_SIZE];
	static unsigned char gsmStr_Idx=0;
	char chrTmp;
	char * strtmp;
	char tmpPhineNumber[MAX_LEN_PHONE_NO];
	strtmp = (char *)malloc(sizeof(char) * 128);
    assert_malloc(strtmp);

	char chkLen;
	
	while(QBuf_Read(&gGSM_RxQBuf, &chrTmp, 1)==QBUF_OK)
	{
		if ((chrTmp==ASC_CR||chrTmp==ASC_LF))
		{
			//process one line string
			if (gsmStr_Idx>GSM_RX_SIZE)
			{
				gsmStr_Idx=GSM_RX_SIZE;
				Console_Out256("gsmStr full\r\n");
			}	
			gsmStr[gsmStr_Idx]=STR_NULL;

			if (gGsm_RespChk[0]!=0) //NULL)
			{
				chkLen=xstrlen(gGsm_RespChk);
				if (chkLen>=GSM_STR_RESP_DTAT_LEN)
				{
					gGsm_RespChk[0]=0;
					Console_Out256("gsmRespChk Err\r\n");
				}
				else
				{
					
					if (strncmp((char *)&gsmStr[0],gGsm_RespChk, chkLen) == 0)
					{
						gGsm_RespChk_Sts=PASS;
						Console_Out256("GsmChk Got It:");
						Console_Out256(gGsm_RespChk);
						Console_Out256("\r\n");
						gGsm_RespChk[0]=0;
						
					}
				}
			}



			if (strncmp((char *)&gsmStr[0], "+CMT:", 5) == 0)
			{	//SMS message incoming message
				//GetStringItem(sTmp1, MDM_RXBUF_SIZE, (char *)uMdmRxBuf[5], ',', 1);
				//if (strlen(sTmp1) > 5)
				//	nSmsIncoming = SMS_TEXT;	//Text mode
				//else
				//nSmsIncoming = SMS_PDU;		//PDU mode
	            //ResetPWRM_COMMTimer();      //Reset T_COMM Timer
	            Console_Out256("SMS Rx<");
				Console_Out256(gsmStr);
				Console_Out256(">\r\n");
			}
			else if (strncmp((char *)&gsmStr[0], "+CLIP", 5) == 0) //+CRING
			{
				Console_Out256("Call in:\r\n");
//				GsmUart_Send("ATH\r\n");
//				qGsm_Send("AT\r\n",500,4,1000,NULL,0);	
				qGsm_Send("ATH\r\n",0,5,0,"OK",1000);	
				GetStringSetItem(gsmStr,tmpPhineNumber,MAX_LEN_PHONE_NO,'"',1);
//				Delay_millisecond(1500);

				sprintf(strtmp, 	"GPS_FIX:%d\r\n"
									"height:%.2f\r\n"
									"Google Map:\r\n"
									"http://maps.google.com/maps?f=q&q=%.6f,%.6f",pUBX->STATUS.gpsFix,(double)pUBX->POSLLH.hMSL*0.001,(double)pUBX->POSLLH.lat*0.0000001,(double)pUBX->POSLLH.lon*0.0000001);

				
				if (xstrlen(tmpPhineNumber)>=10)
				{
					qGsm_AT_CMGS(tmpPhineNumber,strtmp);
				}
				else
				{
					Console_Out256("Err Phone:");
					Console_Out256(tmpPhineNumber);
					Console_Out256("\r\n");
				}
			}

			if (gsmStr[0]!=STR_NULL)
			{
				Console_Out256("[");
				Console_Out256(gsmStr);
				Console_Out256("]\r\n");
			}
			//reset Clean Line
			gsmStr_Idx=0;
			
			
		}
		else
		{
			//save to string line buffer
			if (gsmStr_Idx<GSM_RX_SIZE)
			{
				gsmStr[gsmStr_Idx++]=chrTmp;
			}
			else
			{
				Console_Out256("gsmStr full\r\n");
			}
			
		}
	}


	free(strtmp);
    assert_free();
	
}


void Gsm_Ini_Task(void)
{


		//ATE0 ehco off ,ATE1 echo on (default)
  		//+CMEE=1->enable "+CME ERROR" and "+CMS ERROR"
		//+CREG=1 or 2->enable network registration URC "+CREG"
		//+CGREG=2"
		//+COLP=1 connect to phone call enable message
		//+CLIP=1->enable calling line identification presentation URC "+CLIP"
		//+CRC=1->enable extended ring information, eg:"CRING: VOICE"
		//strcat(sTmp, "CREG=2");
		//strcat(sTmp, ";+CGREG=2");

	char *gGSM_buf;
	
    gGSM_buf = malloc(sizeof(char) * 128);
    assert_malloc(gGSM_buf);	
	
Delay_millisecond(500);
		GSM_PW_OFF();
				Delay_millisecond(500);
		GSM_PW_ON();	//fenris 20110607 test
				Delay_millisecond(1000);

//rex SMS
		pw_led_on();
		Console_Out256("GSM Initiation\r\n");

/*
		pw_led_toggle();
		Console_Out256("ATI\r\n");
		GsmUart_Send("ATI\r\n");
Delay_millisecond(100);//Delay_Sec(2);
//		GsmUart_Display(gGSM_buf);
*/

/*
		pw_led_toggle();
		Console_Out256("at+cpin?\r\n");
		GsmUart_Send("at+cpin?\r\n");
Delay_millisecond(100);//Delay_Sec(2);
//		GsmUart_Display(gGSM_buf);
*/
		pw_led_toggle();
	GsmUart_Send("ATE0\r\n");
	Delay_millisecond(200);
//	Console_Out256("CMEE\r\n");
		GsmUart_Send("AT+CMEE=1\r\n");
	Delay_millisecond(200);	
		GsmUart_Send("AT+CMEE?\r\n");
	Delay_millisecond(200);	
GsmUart_Display(gGSM_buf);


Console_Out256("CLIP\r\n");
		GsmUart_Send("AT+CLIP=1\r\n");			//
			Delay_millisecond(200);	
		GsmUart_Send("AT+CLIP=1\r\n");			//
	Delay_millisecond(500);
	GsmUart_Display(gGSM_buf);
/*
pw_led_toggle();
Console_Out256("AT+CLIP?\r\n");
		GsmUart_Send("AT+CLIP?\r\n");
	Delay_millisecond(4000);
GsmUart_Display(gGSM_buf);
*/

/*
Console_Out256("COLP\r\n");
		GsmUart_Send("AT+COLP=1\r\n");			//
	Delay_millisecond(1000);
		GsmUart_Send("AT+COLP?\r\n");
	Delay_millisecond(3000);	
GsmUart_Display(gGSM_buf);
*/

Console_Out256("CRC\r\n");
		GsmUart_Send("AT+CRC=1\r\n");
	Delay_millisecond(200);
	GsmUart_Send("AT+CRC=1\r\n");
Delay_millisecond(500);
GsmUart_Display(gGSM_buf);





//Console_Out256("AT+CRC?\r\n");
//		GsmUart_Send("AT+CRC?\r\n");
//	Delay_millisecond(2000);
//GsmUart_Display(gGSM_buf);



//Console_Out256("CREG\r\n");
		GsmUart_Send("AT+CREG=2\r\n");
	Delay_millisecond(200);	
		GsmUart_Send("AT+CREG?\r\n");
	Delay_millisecond(200);	
GsmUart_Display(gGSM_buf);
//Console_Out256("CGREG\r\n");
		GsmUart_Send("AT+CGREG=2\r\n");			//
	Delay_millisecond(200);
		GsmUart_Send("AT+CGREG?\r\n");
	Delay_millisecond(2000);	
GsmUart_Display(gGSM_buf);




		pw_led_toggle();
//		Console_Out256("AT+CMGF? and set\r\n");
		GsmUart_Send("AT+CMGF=1\r\n");
Delay_millisecond(200);
	//	Delay_Sec(3);
	//	GsmUart_Display(gGSM_buf);
		GsmUart_Send("AT+CMGF?\r\n");
Delay_millisecond(200);//Delay_Sec(2);Delay_Sec(2);
		GsmUart_Display(gGSM_buf);

pw_led_toggle();
//		Console_Out256("AT+CNMI\r\n");
		GsmUart_Send("AT+CNMI=2,2,0,0,0\r\n");
		Delay_millisecond(200);
		GsmUart_Send("AT+CNMI?\r\n");
//		GsmUart_Display(gGSM_buf);


		//GsmUart_AT_CMGS(TELPHONE_NO,"GSM Test Start");

#if 0
		pw_led_toggle();
		Console_Out256("at+csq\r\n");
		GsmUart_Send("at+csq\r\n");
#endif

		Delay_Sec(2);
		GsmUart_Display(gGSM_buf);
		
		pw_led_toggle();
		if (xstrlen(pCMD->smsdst.num)>=10)
		{
			GsmUart_AT_CMGS(pCMD->smsdst.num,"GSM Test Start");
		}
		else
		{
			Console_Out256("PhoneNo Error=");
			Console_Out256(pCMD->smsdst.num);
			Console_Out256("\r\n");
		}
	pw_led_off();	

		
//AGPS

/*	
qGsm_Send("AT+COPS?\r\n",3*OS_100MS,sizeof("AT+COPS?\r\n"),0,"+COPS:",2*OS_1SEC);
qGsm_Send("AT+UGIND=1\r\n",3*OS_100MS,sizeof("AT+UGIND=1\r\n"),0,"OK",2*OS_1SEC);
qGsm_Send("AT+UGPS=1,1\r\n",3*OS_100MS,sizeof("AT+UGPS=1,1\r\n"),0,"+UUGIND:",5*OS_1SEC);
qGsm_Send("AT+UGPS=0\r\n",OS_1SEC,sizeof("AT+UGIND=1\r\n"),0,"OK",5*OS_1SEC);
*/

qGsm_AtCmd("+COPS?",3*OS_100MS,0,"+COPS:",2*OS_1SEC);
qGsm_AtCmd("+UGIND=1",3*OS_100MS,0,"OK",2*OS_1SEC);
qGsm_AtCmd("+UGPS=1,1",3*OS_100MS,0,"+UUGIND:",5*OS_1SEC);
qGsm_AtCmd("+UGPS=0",OS_1SEC,0,"OK",5*OS_1SEC);

  		TaskDel(Gsm_Ini_Task);
		TaskAdd(Gsm_Task, OS_100MS);	// 100 ms

	free(gGSM_buf);
    assert_free();
	
}

void Gsm_Task(void)
{
	//SendSMS_Test();

	GsmSend_Process();
	GsmRecv_Parser();
}



#if 0

#define AT_STARTUP  		1	//ate0
#define AT_SIMCOM_Ver		2
#define AT_INITIAL          3   //at+cmee=1;+creg=1;+clip=1;+crc=1
#define AT_GSN				4	//at+wimei?
#define AT_CLTS				6	//at+wind=8192
#define AT_STSF				7	//at+stsf=0
#define AT_CPIN				8	//at+cpin?
#define AT_CMGF				9	//at+cmgf=0
#define AT_COPS				10	//at+cmgf=0
#define AT_CSQ				11	//at+csq
#define AT_ATD				12	//ATD
#define AT_ATH				13	//ATH
#define AT_ATA				14	//ATA
#define AT_CBAND			15	//at+cband?

//#ifdef	Add_CellID_6
#define AT_CENG				16	//at+ceng? "Cell ID"
//#endif


#define AT_CREG				21	//at+creg?
#define AT_CGREG			22	//at+creg?
#define AT_CPIN_CODE        31  //at+cpin=1234

#define AT_IPR				41
#define AT_IPR_57600		42
#define AT_AT				43

#define OPENAT_ON			101	//at+wopen=1
#define	WIND_OFF			102	//at+wind=0
#define	AT_CSTT				103	//at+cstt=<apn>,<user>,<pwd>
#define	AT_CIICR			104	//at+ciicr
#define	AT_CIFSR			105	//at+cifsr
#define AT_CIPHEAD			106
#define	AT_CIPSTART			107	//at+cipstart=<index>,<tcp/udp>,<ip>,<port>
#define	AT_CIPCLOSE			111	//at+cipclose
#define	AT_CIPSHUT			112	//at+cipshut
#define	OPENAT_OFF			113	//at+wopen=0

void mdmSendSingleCmd(u8 iCmdId)
{
	char sTmp[64];
	long iATRespVal=0;
	char WaitCMD=0,MICGain=0,llIMEI=0,IPTYPE=0;
	char nCpinNeeded=0,PinCode=0,GolbPhoneNumber=0,SetBandMode=0;
	sTmp[0] = 'A';
	sTmp[1] = 'T';
	sTmp[2] = '+';
	sTmp[3] = STR_NULL;
	WaitCMD = iCmdId;
	switch(iCmdId)
	{
	case AT_STARTUP:
		//ATE0->echo off
		sprintf(sTmp, "ATE0");				//
		strcat(sTmp, ";+CMEE=1");			//
		break;
    case AT_SIMCOM_Ver:
		strcat(sTmp, "GMR");
		break;
    case AT_INITIAL:
  		//+CMEE=1->enable "+CME ERROR" and "+CMS ERROR"
		//+CREG=1->enable network registration URC "+CREG"
		//+CLIP=1->enable calling line identification presentation URC "+CLIP"
		//+CRC=1->enable extended ring information, eg:"CRING: VOICE"
		//strcat(sTmp, "CREG=2");
		//strcat(sTmp, ";+CGREG=2");
		sprintf(sTmp, "AT+CMIC=0,%d",MICGain);
		strcat(sTmp, ";+CREG=2");			//
		strcat(sTmp, ";+CGREG=2");			//
		strcat(sTmp, ";+COLP=1");			//
		strcat(sTmp, ";+VTD=2");
		strcat(sTmp, ";+CLIP=1");			//
		strcat(sTmp, ";+CRC=1");			//
		strcat(sTmp, ";+CSDT=1");
		strcat(sTmp, ";+CFGRI=0");
		strcat(sTmp, ";+CSCLK=1");
		strcat(sTmp, ";+CENG=1,1");// ellis
		strcat(sTmp, ";+ECHO=25000,200,0,0");	
		//strcat(sTmp, ";+SIDET=2048");
		strcat(sTmp, ";+CLVL=100");					//
		strcat(sTmp, ";+SIDET=0");
		strcat(sTmp, ";+CMIC=1,0");
		strcat(sTmp, ";+ECHO=32767,32767,0,0");
                
            //    #ifdef USING_IVR
		    strcat(sTmp, ";+CHFA=1");					// John 20090828, for IVR
            //    #endif
                    
		break;
		
	case AT_AT:
		sprintf(sTmp, "AT\rAT");
		break;
	case AT_IPR:
		//+CPIN?->request SIM card status. We can't move on if SIM card is not
		//  ready.
		strcat(sTmp, "IPR");
		strcat(sTmp, "?");
		break;
	case AT_IPR_57600:
		if (iATRespVal != 57600)
		{
			strcat(sTmp, "IPR");
			strcat(sTmp, "=57600;&W");
		}
		else
		{	
			WaitCMD =0 ;
			return;
		}
		break;
	case AT_GSN:
		if(llIMEI==0)
		{
			//IMEI_Flag=1;
			strcat(sTmp, "GSN");			
		}
		else
		{
			WaitCMD =0 ;
			return;
		}
		break;
	case AT_COPS:
		strcat(sTmp, "COPS?");
		break;
		
		
//	#ifdef	Add_CellID_6
	case AT_CENG:	
		strcat(sTmp, "CENG?");

		break;
//	#endif	
		
	case AT_CPIN:
		//+CPIN?->request SIM card status. We can't move on if SIM card is not
		//  ready.
		strcat(sTmp, "CPIN");
		strcat(sTmp, "?");
		break;
    case AT_CPIN_CODE:
        if (nCpinNeeded == TRUE)
        {
            if (strlen(PinCode) > 0)
            {
                strcat(sTmp, "CPIN=");
    		    strcat(sTmp, PinCode);
            }
            else
            {
                strcat(sTmp, "CPIN");
	        	strcat(sTmp, "?");
            }
        }
		
        else
		{
			WaitCMD =0 ;
            return;
			//sprintf(sTmp, "ATE0");
		}
        break;
	case AT_CMGF:
		//+CNMI=2,2,0,0,0->enable SMS by URC "+CMT:<length><CR><pdu>"
		//+CMGF=0->use PDU format in SMS read/write
		strcat(sTmp, "CNMI=2,2,0,0,0;+CMGF");
		//strcat(sTmp, "CMGF");
		strcat(sTmp, "=0");
		break;
	case AT_ATD:
//		strcat(sTmp, "CMIC=0,15;D");
		sprintf(sTmp, "ATD");
		strcat(sTmp, (char*)GolbPhoneNumber);
		strcat(sTmp, ";");
		break;
	case AT_ATH:
		sprintf(sTmp, "ATH");
//		strcat(sTmp, "+CMIC=0,1");
		break;
	case AT_ATA:
		sprintf(sTmp, "ATA");
//		strcat(sTmp, "+CMIC=0,15");
		break;
		
	case AT_CBAND:
		if(SetBandMode==1)
		{
			strcat(sTmp, "CBAND=\"EGSM_DCS_MODE\"");
		}
		else if(SetBandMode==2)
		{
			strcat(sTmp, "CBAND=\"GSM850_PCS_MODE\"");
		}
		else
		{
			strcat(sTmp, "CBAND");
			strcat(sTmp, "?");
		}
			
		break;
	case AT_CREG:
		//+CREG?->request network registration status
		strcat(sTmp, "CREG");
		strcat(sTmp, "?");
		break;
	case AT_CGREG:
		//+CREG?->request network registration status
		strcat(sTmp, "CGREG");
		strcat(sTmp, "?");
		break;
	case AT_CSQ:
		//+CSQ->request signal quality
		strcat(sTmp, "CSQ");
		break;
	case AT_CLTS:
		strcat(sTmp, "CLTS");
		break;
/*	case AT_STSF:
		//+STSF=0->deactivates SIM ToolKit functionalities.
		strcat(sTmp, "STSF");
		strcat(sTmp, "=0");
	 	break;*/
	case WIND_OFF:
		strcat(sTmp, "WIND");
		strcat(sTmp, "=0");
		break;
	case AT_CSTT:
		//ST defined command
		char APN=0, Username=0, LoginPassword=0;
		sprintf(sTmp, "AT+CSTT=\"%s\",\"%s\",\"%s\"", APN, Username, LoginPassword);
		break;
	case AT_CIICR:
		//ST defined command
		strcat(sTmp, "CIICR");
		break;
	case AT_CIFSR:
		//ST defined command
		strcat(sTmp, "CIFSR");
		break;
	case AT_CIPHEAD:
		strcat(sTmp, "CIPHEAD=1");
		break;
	case AT_CIPSTART:
		//ST defined command
		//sprintf(sTmp, "AT+CIPSTART=0,\"UDP\",\"%s\",\"%d\"\r\n",
		char sHostIP=0,HostPort=0;
		if(IPTYPE)
		{
			sprintf(sTmp, "AT+CIPSTART=\"TCP\",\"%s\",\"%d\"",sHostIP, HostPort);
		}
		else
		{
			sprintf(sTmp, "AT+CIPSTART=\"UDP\",\"%s\",\"%d\"",sHostIP, HostPort);
		}
		break;
	case AT_CIPCLOSE:
		//ST defined command
		strcat(sTmp, "CIPCLOSE");
		break;
	case AT_CIPSHUT:
		//ST defined command
		strcat(sTmp, "CIPSHUT");
		break;
	default:
		sprintf(sTmp, "Unknown CmdId %d", iCmdId);
//		conDebugPrint(sTmp);
		WaitCMD =0 ;
		return;
	}
	

}
#endif

/** @} */
